import { useState, useRef, useEffect } from "react";
import { Input, Button, Space, Divider, Empty, message } from "antd";
import { SendOutlined, RobotOutlined, UserOutlined } from "@ant-design/icons";
import type { Article } from "../types";

const { TextArea } = Input;

interface Message {
  id: string;
  role: "user" | "assistant";
  content: string;
  timestamp: Date;
}

interface AIChatPanelProps {
  article: Article | null;
}

export default function AIChatPanel({ article }: AIChatPanelProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 当文章切换时，初始化对话（AI 开场白显示文章摘要）
  useEffect(() => {
    if (article) {
      const summary =
        article.ai_summary || generateSummaryFromContent(article.content);

      setMessages([
        {
          id: `ai-${Date.now()}`,
          role: "assistant",
          content: `📚 **文章摘要**\n\n${summary}\n\n---\n\n有什么想要了解的吗？我可以帮你解答关于这篇文章的任何问题。`,
          timestamp: new Date(),
        },
      ]);
    } else {
      setMessages([]);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [article?.id]);

  // 自动滚动到底部
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  // 从文章内容截取摘要（移除 HTML 标签）
  const generateSummaryFromContent = (content: string): string => {
    const textContent = content
      .replace(/<[^>]*>/g, "")
      .replace(/\s+/g, " ")
      .trim();
    return (
      textContent.substring(0, 200) + (textContent.length > 200 ? "..." : "")
    );
  };

  // 发送消息
  const handleSend = async () => {
    if (!inputValue.trim() || !article) {
      return;
    }

    const userMessage: Message = {
      id: `user-${Date.now()}`,
      role: "user",
      content: inputValue.trim(),
      timestamp: new Date(),
    };

    setMessages((prev) => [...prev, userMessage]);
    setInputValue("");
    setIsLoading(true);

    try {
      // TODO: 调用后端 AI API（目前使用模拟响应）
      await new Promise((resolve) => setTimeout(resolve, 1000));

      const aiMessage: Message = {
        id: `ai-${Date.now()}`,
        role: "assistant",
        content: `🤖 这是一个模拟回复。\n\n你提问了："${userMessage.content}"\n\n实际的 AI 对话功能正在开发中，将会集成 Coze API 来提供智能问答服务。`,
        timestamp: new Date(),
      };

      setMessages((prev) => [...prev, aiMessage]);
    } catch {
      message.error("AI 响应失败，请稍后重试");
    } finally {
      setIsLoading(false);
    }
  };

  // 按 Enter 发送（Shift+Enter 换行）
  const handleKeyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  if (!article) {
    return (
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          height: "100%",
          background: "#fafafa",
        }}
      >
        <Empty
          description={
            <span style={{ fontSize: "16px", color: "#8c8c8c" }}>
              请选择文章开始对话
            </span>
          }
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      </div>
    );
  }

  return (
    <div
      style={{
        height: "100%",
        display: "flex",
        flexDirection: "column",
        background: "#fff",
      }}
    >
      {/* 头部 */}
      <div
        style={{
          padding: "20px 24px",
          borderBottom: "1px solid #e8e8e8",
          background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
        }}
      >
        <div
          style={{
            fontSize: "18px",
            fontWeight: 600,
            color: "#fff",
            display: "flex",
            alignItems: "center",
            gap: "8px",
          }}
        >
          <RobotOutlined style={{ fontSize: "20px" }} />
          AI 助手
        </div>
        <div
          style={{
            fontSize: "13px",
            color: "rgba(255,255,255,0.85)",
            marginTop: "6px",
          }}
        >
          基于文章内容的智能问答
        </div>
      </div>

      {/* 消息列表 */}
      <div
        style={{
          flex: 1,
          overflowY: "auto",
          padding: "24px",
          background: "#fafafa",
        }}
      >
        {messages.map((msg) => (
          <div
            key={msg.id}
            style={{
              marginBottom: "20px",
              display: "flex",
              gap: "12px",
              alignItems: "flex-start",
            }}
          >
            {/* 头像 */}
            <div
              style={{
                width: "36px",
                height: "36px",
                borderRadius: "50%",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                flexShrink: 0,
                background:
                  msg.role === "assistant"
                    ? "linear-gradient(135deg, #667eea 0%, #764ba2 100%)"
                    : "#1890ff",
                color: "#fff",
                fontSize: "16px",
              }}
            >
              {msg.role === "assistant" ? <RobotOutlined /> : <UserOutlined />}
            </div>

            {/* 消息内容 */}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div
                style={{
                  fontSize: "13px",
                  color: "#8c8c8c",
                  marginBottom: "6px",
                }}
              >
                {msg.role === "assistant" ? "AI 助手" : "我"}
              </div>
              <div
                style={{
                  background: "#fff",
                  padding: "12px 16px",
                  borderRadius: "8px",
                  fontSize: "15px",
                  lineHeight: "1.6",
                  color: "#333",
                  whiteSpace: "pre-wrap",
                  wordBreak: "break-word",
                  boxShadow: "0 2px 8px rgba(0,0,0,0.05)",
                }}
              >
                {msg.content}
              </div>
            </div>
          </div>
        ))}

        {isLoading && (
          <div
            style={{ textAlign: "center", color: "#8c8c8c", fontSize: "14px" }}
          >
            🤔 AI 正在思考...
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      <Divider style={{ margin: 0 }} />

      {/* 输入框 */}
      <div style={{ padding: "16px 24px", background: "#fff" }}>
        <Space.Compact style={{ width: "100%" }}>
          <TextArea
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="输入你的问题... (Enter 发送, Shift+Enter 换行)"
            autoSize={{ minRows: 1, maxRows: 4 }}
            style={{ fontSize: "14px" }}
            disabled={isLoading}
          />
          <Button
            type="primary"
            icon={<SendOutlined />}
            onClick={handleSend}
            loading={isLoading}
            disabled={!inputValue.trim()}
            style={{ height: "auto" }}
          >
            发送
          </Button>
        </Space.Compact>
      </div>
    </div>
  );
}
